using System;
using System.Runtime.InteropServices;

namespace sforceExplorer
{
	/// <summary>
	/// Summary description for TreeViewExtender.
	/// </summary>
	public class TreeViewExtender
	{
		private const int TVIS_STATEIMAGEMASK = 0xF000; 
		private const int     TVIF_TEXT = 0x0001, 
			TVIF_IMAGE = 0x0002, 
			TVIF_STATE = 0x0008, 
			TVIF_HANDLE = 0x0010, 
			TVIF_SELECTEDIMAGE = 0x0020, 
			TVM_SETITEM = 0x110D; 


		[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] 
			private class TVITEM 
		{ 
			public int                  mask; 
			public System.IntPtr         hItem; // HTREEITEM 
			public int                  state; 
			public int                  stateMask;    
			public System.IntPtr         pszText;   // string 
			public int                  cchTextMax; 
			public int                  iImage; 
			public int                  iSelectedImage; 
			public int                  cChildren; 
			public System.IntPtr         lParam; 
		} 

		static public void RemoveCheckBoxFromNode(System.Windows.Forms.TreeNode node) 
		{ 
			// 
			// It is important that the TreeView.Handle is accessed before 
			// the TreeNode Handle. If it is not, the results of TreeNode.Handle 
			// are non-deterministic. 
			// 

			System.IntPtr treeViewHandle = node.TreeView.Handle; 

			TVITEM tvi = new TVITEM(); 
			tvi.hItem = node.Handle; 
			tvi.mask = TVIF_HANDLE | TVIF_STATE; 
			tvi.stateMask = TVIS_STATEIMAGEMASK; 
			tvi.state = 0; 

			User32.SendMessage(treeViewHandle, TVM_SETITEM, System.IntPtr.Zero, tvi); 
		}

		static public void RemoveImageFromNode(System.Windows.Forms.TreeNode node) 
		{ 
			// 
			// It is important that the TreeView.Handle is accessed before 
			// the TreeNode Handle. If it is not, the results of TreeNode.Handle 
			// are non-deterministic. 
			// 

			System.IntPtr treeViewHandle = node.TreeView.Handle; 

			TVITEM tvi = new TVITEM(); 
			tvi.hItem = node.Handle; 
			tvi.mask = TVIF_HANDLE | TVIF_IMAGE | TVIF_SELECTEDIMAGE; 
			tvi.iImage = -1;
			tvi.iImage = -1;
			tvi.stateMask = TVIS_STATEIMAGEMASK; 
			tvi.state = 0; 

			User32.SendMessage(treeViewHandle, TVM_SETITEM, System.IntPtr.Zero, tvi); 
		}

		static public bool HasCheckBox(System.Windows.Forms.TreeNode node) 
		{ 
			const int TVM_GETITEMSTATE = 0x1127; 
			System.IntPtr treeViewHandle = node.TreeView.Handle; 

			System.IntPtr res = User32.SendMessage(treeViewHandle, 
				TVM_GETITEMSTATE, node.Handle, TVIS_STATEIMAGEMASK); 

			return ((res.ToInt32() & 0x1000) > 0) || ((res.ToInt32() & 0x2000) > 0); 
		} 
	}

	public class User32 
	{ 
		[DllImport("user32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)] 
		internal static extern System.IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, [In, Out, MarshalAs(UnmanagedType.AsAny)] Object lParam); 
	} 
}
